/*
 * as_lesson_yuv.cpp
 *
 *  This is a file to show how to use SDL2 to render yuv in android
 *      Author: Tocy
 *		any questions please contact me by zyvj@qq.com.
 */

#include "as_lesson_log.h"
#include "SDL.h"


struct AudioPlayContext 
{
	//Uint8 * data; // pcm buffer
	//int data_len; // left data length
	bool is_exit; // is audio play buffer empty?
	FILE * fpcm;
};

void MyAudioCallback(void* userdata, Uint8* stream, int need_size)
{
	AudioPlayContext * context = reinterpret_cast<AudioPlayContext *>(userdata);
	
	size_t actual_read = fread(stream, 1, need_size, context->fpcm);
	
	if (0 == actual_read || feof(context->fpcm))
	{
	    LOGD("we meet stream end %u", actual_read);
		context->is_exit = true;
	}
}

extern "C" int pcm_main(int argc, char *argv[]) 
{
    // init sdl
    if (0 != SDL_Init(SDL_INIT_AUDIO))
    {
        LOGE("%s %d SDL init audio failed", __FUNCTION__, __LINE__);
        return -1;
    }
    AudioPlayContext ctx;
    ctx.is_exit = false;
    ctx.fpcm = NULL;
    
    // load yuv
    const char *pcm_path = "/sdcard/congtou_8k_mono_16bit.pcm";
    LOGI("natvie_SDL load pcm %s", pcm_path); 
    ctx.fpcm = fopen(pcm_path, "rb");
    if (NULL == ctx.fpcm)
    {
        LOGE("%s %d load pcm failed path %s", __FUNCTION__, __LINE__, pcm_path);
        SDL_Quit();
        return -2;
    }
    
    
    // open audio device
	SDL_AudioSpec want, have;
    SDL_memset(&want, 0, sizeof(want)); /* or SDL_zero(want) */
    SDL_memset(&want, 0, sizeof(have)); /* or SDL_zero(want) */
	want.freq = 8000;
	want.format = AUDIO_S16LSB;
	want.channels = 1;
	want.samples = 1024;
	want.callback = MyAudioCallback;  // you wrote this function elsewhere.
	want.userdata = &ctx;

	if (SDL_OpenAudio(&want, &have) < 0) 
	{
		LOGE("Failed to open audio: %s", SDL_GetError());
		SDL_Quit();
		return -3;
	}
	
	if (have.format != want.format)
	{	
	    LOGD("We didn't get AUDIO_S16LSB audio format want %d have %d", want.format, have.format);
	}
	
	// start audio playing.
	SDL_PauseAudio(0);  
	// wait for the end
	while (!ctx.is_exit)
	{
		SDL_Delay(1000);
	}
	
	SDL_CloseAudio();
	fclose(ctx.fpcm);
	//if (NULL != ctx.data)
	//    delete [] ctx.data;	
    
    // Quit SDL
    SDL_Quit();
	
    return 0;
}
